package com.demo.gateway.app.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Value("${servername:}")
    private String servername;

    /**
     * 测试接口功能
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("")
    public String demo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("{}接收到请求,参数：{},查询字符串{}",servername,request.getParameterMap(),request.getQueryString());

        // header
        log.info("------------------header------------------");
        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()) {
            String headerkey = headerNames.nextElement();
            log.info("header:{},---->val:{}",headerkey,request.getHeaders(headerkey));
        }
        //parameter
        log.info("------------------parameter------------------");
        request.getParameterMap().forEach((key,val) -> {
            log.info("parameter:{},------>{}",key,val);
        });
        // attr
        log.info("------------------attr------------------");
        Enumeration<String> attr = request.getAttributeNames();
        while(attr.hasMoreElements()) {
            String key = attr.nextElement();
            log.info("attr:{},---->val:{}",key,request.getAttribute(key));
        }
        // body
        log.info("------------------body------------------");
        byte[] b = IOUtils.toByteArray(request.getInputStream());
        log.info("body:{}",new String(b));
        /*InputStream in = request.getInputStream();
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int length; (length = in.read(buffer)) != -1; ) {
            result.write(buffer, 0, length);
        }
        String content = result.toString(StandardCharsets.UTF_8.name());
        log.info("body:{}",content);
        */
        return servername + "------" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 模拟后端常见的NPE异常
     */
    @RequestMapping("/npe")
    public void npe(){
        throw new NullPointerException("手动的NPE异常！");
    }
}
